package model

import (
	"errors"
	"github.com/jinzhu/gorm"
)

// AlgorithmInfo Algorithm structure
type AlgorithmInfo struct {
	gorm.Model
	Name          string `json:"name"`
	Version       string `json:"version"`
	Type          int64  `json:"type"`
	AlgorithmPath string `json:"algorithm_path"`
	ModelPath     string `json:"model_path"`
	ConfigPath    string `json:"config_path"`
	Description   string `json:"description"`
	UserID        int64  `json:"user_id"`
}

// AddNewAlgo add a new Algorithm
func AddNewAlgo(algoInfo *AlgorithmInfo) (interface{}, error) {
	algo := db.Save(algoInfo)
	return algo.Value, nil
}

// ExistAlgoByName check the algorithm name is exist or not
func ExistAlgoByName(name string) bool {
	var algo AlgorithmInfo
	db.Select("id").Where("name = ?", name).First(&algo)
	if algo.ID > 0 {
		return true
	}
	return false
}

// GetAlgo get a single Algo
func GetAlgo(algoID string) (*AlgorithmInfo, error) {
	var algo AlgorithmInfo
	// SELECT * FROM Algo WHERE id = AlgoID;
	db.First(&algo, algoID)
	if algo.ID == 0 {
		err := errors.New("no Algo found")
		return &AlgorithmInfo{}, err
	}
	return &algo, nil
}

// GetAlgoWithType get a single Algo
func GetAlgoWithType(algoType string, userID string) ([]AlgorithmInfo, error) {
	var algo []AlgorithmInfo

	if algoType == "" {
		db.Where("user_id = ?", userID).Find(&algo)
	} else if userID == "" {
		db.Where("type = ?", algoType).Find(&algo)
	} else {
		db.Where("type = ? AND user_id = ?", algoType, userID).Find(&algo)
	}

	if len(algo) == 0 {
		err := errors.New("no Algo found")
		return []AlgorithmInfo{}, err
	}

	return algo, nil
}

// ExistAlgoByID check the id is exist or not
func ExistAlgoByID(ID int) bool {
	var myAlgo AlgorithmInfo
	db.Select("id").Where("id = ?", ID).First(&myAlgo)
	if myAlgo.ID > 0 {
		return true
	}
	return false
}

// UpdateAlgo edit user info
func UpdateAlgo(id int, data interface{}) bool {
	db.Model(&AlgorithmInfo{}).Where("id = ?", id).Updates(data)

	return true
}

// DeleteAlgo delete the user info from db
func DeleteAlgo(id int) bool {
	db.Where("id = ?", id).Delete(&AlgorithmInfo{})

	return true
}

// GetAllAlgos get the all Algos info from db
func GetAllAlgos() (result []AlgorithmInfo, err error) {
	var myAlgo []AlgorithmInfo
	db.Find(&myAlgo)

	if len(myAlgo) == 0 {
		err = errors.New("no Algo found")
		return nil, err
	}
	return myAlgo, nil
}
